package com.tuanzi.loan.web.bean.channel;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.common.CommProductChannel;
import com.tuanzi.loan.business.service.common.CommProductChannelService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.channel.ChannelBatchRequest;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.CHANNEL_GROUP;

@Debug
@Component
@ViewScoped
public class ChannelBatchInfoBean extends JSFInfoBean<ChannelBatchRequest> {

	private static final long serialVersionUID = -2152778554108785342L;
	@Autowired
	private CommProductChannelService commProductChannelService;

	@PostConstruct
	private void init() {
		$ = new ChannelBatchRequest();
	}

	public void onSave() {
		if ($.getStartChannelCode() == null) {
			addErrorMessage("起始渠道编号不能为空");
			return;
		}
		if ($.getEndChannelCode() == null) {
			addErrorMessage("终止渠道编号不能为空");
			return;
		}
		if ($.getProductId() == null) {
			addErrorMessage("所属产品不能为空");
			return;
		}
		if ($.getChannelGroup() == null) {
			addErrorMessage("起始渠道编号不能为空");
			return;
		}
		if ($.getStartChannelCode() >= $.getEndChannelCode()) {
			addErrorMessage("终止渠道编号需大于起始渠道编号");
			return;
		}
		if ($.getEndChannelCode() - $.getStartChannelCode() >= 50) {
			addErrorMessage("一次最多只能批量增加50个渠道编号");
			return;
		}

		Integer count = commProductChannelService.checkDuplicatedChannelCode($.getStartChannelCode(), $.getEndChannelCode());
		if(count != null && count > 0) {
			addFiledMessage("这批渠道号中已存在部分渠道号");
			return;
		}
		List<CommProductChannel> list = Lists.newArrayList();
		for (int i = $.getStartChannelCode(); i <= $.getEndChannelCode(); i++) {
			CommProductChannel c = new CommProductChannel();
			c.setChannelCode(i);
			c.setChannelName($.getChannelName());
			c.setProductId($.getProductId());
			c.setChannelGroup($.getChannelGroup());
			list.add(c);
		}
		commProductChannelService.batchSave(list);
		$ = new ChannelBatchRequest();
		addSuccessfullyMessage();
	}

	public String onBatchAdd() {
		return redirect("/views/channel/batch-info.xhtml");
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(CHANNEL_GROUP);
	}

}
